/* support.c -- Functions that make many support actions, like
 * creating strings
 *
 * Time-stamp: <2007-08-08 04:45:40 BRT Diogo F. S. Ramos>
 *
 *
 */

#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <gtk/gtk.h>

#include "support.h"
#include "engcur.h"

/* Functions that involves operations with Strings *******************/

int str_create_copy_string( char **str1, char *str2 )
{
	*str1 = (char*) malloc( ((strlen(str2)+1) * sizeof(char)) );
	strcpy(*str1,str2);
	return 0;
}

int str_change_copy_string( char **str1, char *str2 )
{
	*str1 = (char*) realloc(*str1, (strlen(str2)+1) * sizeof(char) );
	strcpy(*str1,str2);	
	return 0;
}

int str_concat_string( char **str1, char *str2 )
{
	int tam = 0;
	tam = strlen( *str1 );
	tam = tam + strlen( str2 );
	*str1 = (char*) realloc( *str1, (tam+1) * sizeof(char));
	strcat( *str1, str2 );
	return 0; 
}
/*********************************************************************/

/* Time functions */

/* Needs a time vector of 6 */
void
time_toString( char time[], int seconds )
{
//    char time[6];
    int hours;
    int minutes;
    char *ptr;
    
    hours = seconds/3600;
    minutes = (seconds%3600)/60;

    ptr = time;

    if( hours < 10 )
    {
	time[0] = '0';
	ptr++;
	snprintf( ptr, 2, "%d", hours );
    } else {
	snprintf( ptr, 3, "%d", hours );
    }

    time[2] = ':';
    time[3] = '\0';
    ptr = &time[3];

    if( minutes < 10 )
    {
	time[3] = '0';
	ptr++;
	snprintf( ptr, 2, "%d", minutes );	
    } else {
	snprintf( ptr, 3, "%d", minutes );
    }
    time[5] = '\0';

    return;
}

int
time_toInteger( char time[] )
{
    return ( ( ( ( (time[0] - 48) * 10) + (time[1] - 48) ) * 3600 ) +
	     ( ( ( (time[3] - 48) * 10) + (time[4] - 48) ) * 60   ) );
}

/*********************************************************************/

int
day_char_to_int( char *day )
{
    switch( day[2] )
    {
    case 'm':			/* Domingo */
	return SUNDAY;
    case 'g':			/* Segunda */
	return MONDAY;
    case 'r':			/* Terca */
	return TUESDAY;
    case 'a':			/* Quarta */
	return WEDNESDAY;
    case 'i':			/* Quinta */
	return THURSDAY;
    case 'x':			/* Sexta */
	return FRIDAY;
    case 'b':			/* Sabado */
	return SATURDAY;
    default:
	return -1;
    }
}

char*
day_int_to_char( int day )
{
    char *daystr = (char*) malloc( sizeof( char ) * 10 ) ;
    
    switch( day )
    {
    case SUNDAY:			/* Domingo */
	strcpy( daystr, "Domingo");
	break;
    case MONDAY:			/* Segunda */
	strcpy( daystr, "Segunda");
	break;
    case TUESDAY:			/* Terca */
	strcpy( daystr, "Terça");
	break;
    case WEDNESDAY:			/* Quarta */
	strcpy( daystr, "Quarta");
	break;
    case THURSDAY:			/* Quinta */
	strcpy( daystr, "Quinta");
	break;
    case FRIDAY:			/* Sexta */
	strcpy( daystr, "Sexta");
	break;
    case SATURDAY:			/* Sabado */
	strcpy( daystr, "Sábado");
	break;
    default:
	free( daystr );
	daystr = NULL;
	break;
    }

    return daystr;
}
